import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios"
// import router from "@/router"
import { ResponseData } from "@/types"
import { getToken } from "./auth"
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  noLoading?: boolean
}

const config = {
  // 默认地址请求地址
  baseURL: import.meta.env.VITE_API_URL as string,
  // 超时时间
  timeout: 5000
}

class RequestHttp {
  service: AxiosInstance
  public constructor(config: AxiosRequestConfig) {
    // instantiation
    this.service = axios.create(config)

    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (config: CustomAxiosRequestConfig) => {
        if (config.headers && typeof config.headers.set === "function") {
          config.headers.set("Authorization", "Bearer " + getToken())
        }
        return config
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      }
    )

    /**
     * @description 响应拦截器
     *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data } = response

        // 登陆失效
        // if (data.code == 200) {
        //   userStore.setToken("")
        //   router.replace("/login")
        //   return Promise.reject(data)
        // }

        // 成功请求
        return data
      },
      async (error: AxiosError) => {
        // const { response } = error

        // 请求超时 && 网络错误单独判断，没有 response
        // if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时！请您稍后重试")
        // if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误！请您稍后重试")
        // 根据服务器响应的错误状态码，做不同的处理
        // if (response) {
        //   checkStatus(response.status)
        // }
        return Promise.reject(error)
      }
    )
  }

  /**
   * @description 常用请求方法封装
   */
  get<T>(url: string, params?: object, _object = {}): Promise<ResponseData<T>> {
    return this.service.get(url, { params, ..._object })
  }
  post<T>(url: string, params?: object | string, _object = {}): Promise<ResponseData<T>> {
    return this.service.post(url, params, _object)
  }
  put<T>(url: string, params?: object, _object = {}): Promise<ResponseData<T>> {
    return this.service.put(url, params, _object)
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResponseData<T>> {
    return this.service.delete(url, { params, ..._object })
  }
  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: "blob" })
  }
}

export default new RequestHttp(config)
